package com.tianzhu.config;

import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;


public class CustomAuthenticationProvider implements AuthenticationProvider {

	

	private UserDetailsService userDetailService;
	
	private PasswordEncoder passwordEncoder;
	
	public CustomAuthenticationProvider(UserDetailsService userDetailService,
			PasswordEncoder passwordEncoder) {
		this.userDetailService = userDetailService;
		this.passwordEncoder = passwordEncoder;
	}
	
	@Override
	public Authentication authenticate(Authentication authentication)
			throws AuthenticationException {
		UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication;
		String uname = token.getPrincipal().toString();
		UserDetails userDetails = userDetailService.loadUserByUsername(uname);
		if(!passwordEncoder.matches(token.getCredentials().toString(), userDetails.getPassword())){
			
			throw new BadCredentialsException("The credentails are invalid");
		}
		return new UsernamePasswordAuthenticationToken(userDetails,userDetails.getPassword(),userDetails.getAuthorities());
	}

	@Override
	public boolean supports(Class<?> authentication) {
		
		return UsernamePasswordAuthenticationToken.class.equals(authentication);
	}

}
